﻿#include <QString>
#include <QDataStream>
#include <QDebug>
#include "notifyFromTcpServer.h"
#include "notifyWidgetManager.h"
/* 消息结构体，与客户端保持一致 */
struct notify_message {
    int token;
    char tittle[128];
    char message[128];
    int  duration;
    char type[128];
    char url[128];
};

notifyFromTcpServer::notifyFromTcpServer()
{
    mtopConfig = topConfig::getInstance();
    bindPort = mtopConfig->getBindPort();

    m_tcpServer = new QTcpServer();

    isEnableUrl = mtopConfig->isEnableRemoteNotifyURL();
    mToken = mtopConfig->getRemoteToken();
    m_tcpServer->listen(QHostAddress::Any, bindPort);
    connect(m_tcpServer, SIGNAL(newConnection()), this, SLOT(acceptConnection()));
}

void notifyFromTcpServer::acceptConnection()
{
    m_tcpSocket = m_tcpServer->nextPendingConnection();
    connect(m_tcpSocket, SIGNAL(readyRead()), this, SLOT(requestIn()));
    connect(m_tcpSocket, SIGNAL(disconnected(void)), this, SLOT(disconnectHandle(void)), Qt::QueuedConnection);
}

void notifyFromTcpServer::requestIn()
{
    QByteArray  buffer;

    struct notify_message *get_Data;

    // 接收数据， 通知UI 更新
    if(m_tcpSocket->bytesAvailable() > 0)
    {
        buffer  = m_tcpSocket->readAll();
        if(buffer.isEmpty())
        {
            return;
        }
        get_Data = (struct notify_message *) buffer.data();  //强转为结构体，需要用结构体指针接收
        int token = get_Data->token;
        if(token != mToken)
        {
            return ;
        }
        QString type(get_Data->type);
        int durationSec = get_Data->duration;
        QString msg(get_Data->message);
        QString tittle(get_Data->tittle);
        // 收到的URL 不一定会被使用
        QString url(get_Data->url);
        if(!isEnableUrl)
        {
            url = "";
        }
#if 0
        qDebug() << type;
        qDebug() << durationSec;
        qDebug() << msg;
        qDebug() << tittle;
        qDebug() << url;
#endif
        NotifyManager::getInstance()->showSystemMessage(tittle, msg, url, durationSec, type);
    }
}

void notifyFromTcpServer:: disconnectHandle(void)
{
    m_tcpSocket->disconnect();
}
